using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Forecast.Database;
using Forecast.Business;

public partial class Main : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        _adminMenu.Visible = this.Page.User.IsInRole("Admin");       
    }

    protected void _loginClick(object sender, EventArgs e)
    {
        Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        activity.UpdateAllPlayers();
    }

    private TraderOverview _traderOverview = null;
    protected string GetCash()
    {
        InitTraderOverview();

        string cash = String.Format("{0:#,0}", _traderOverview.Cash);
        return cash;      
    }

    protected string GetCashInStocks()
    {
        InitTraderOverview();

        string cashInStocks = String.Format("{0:#,0}", _traderOverview.CashInStocks);
        return cashInStocks;
    }

    private void InitTraderOverview()
    {
        if (_traderOverview != null)
            return;
        Load load = new Load(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        Player player = load.GetPlayer(UserHelper.GetUserId(Page.User.Identity.Name));
        Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        _traderOverview = activity.GetTraderOverview(player.Id);
    }

    protected string GetStockValue()
    {
        InitTraderOverview();
        return String.Format("{0:#,0}", _traderOverview.StockValue);
    }

    protected string GetLatest()
    {
        Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        IList<NewsItem> latest = activity.GetLatest();

        string latestText = "";
        foreach (NewsItem newsItem in latest)
        {
            string date = TimespanExtensions.HowLongAgo(newsItem.NewsDate);
            //if (IsToday(newsItem.NewsDate))
            //    date = newsItem.NewsDate.ToShortTimeString();
            //else
            //    date = newsItem.NewsDate.ToShortDateString();

            if (latestText.EndsWith("<br />"))
                latestText += "<br />";
            latestText += "<b>" + date + ":</b>" + Environment.NewLine;
            latestText += newsItem.Message;
            latestText += "<br />";
        }
        return latestText;
    }

    private bool IsToday(DateTime someWhen)
    {
        return (someWhen.Year == DateTime.Today.Year &&
            someWhen.Month == DateTime.Today.Month &&
            someWhen.Day == DateTime.Today.Day);
    }
}
